package demo_basic.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class CloneTest {

    public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
	TestClass ts = new TestClass();
	ts.name = "name1";
	ts.num = 1;
	ts.mem = new TestMem("mem1");
	// TestClass ts2 = (TestClass)ts.clone();
	TestClass ts2 = (TestClass) ts.deepClone();
	ts2.name = "name2";
	ts2.num = 2;
	ts2.mem.name = "mem2";
	System.out.println(ts.name + "	" + ts.num + "	" + ts.mem.name);
	System.out.println(ts2.name + "	" + ts2.num + "	" + ts2.mem.name);
    }

}

class TestClass implements Cloneable, Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    TestMem mem;
    String name;
    int num;

    @Override
    public Object clone() throws CloneNotSupportedException {
	// TODO Auto-generated method stub
	return super.clone();
    }

    public Object deepClone() throws IOException, ClassNotFoundException {
	ByteArrayOutputStream bo = new ByteArrayOutputStream();
	ObjectOutputStream oo = new ObjectOutputStream(bo);
	oo.writeObject(this);

	ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
	ObjectInputStream oi = new ObjectInputStream(bi);
	return (oi.readObject());
    }
}

class TestMem implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    String name;

    public TestMem(String name) {
	super();
	this.name = name;
    }

}